package cn.test;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;

public class TcpMaster {

	private  String  host="192.168.1.122";
	private  int  port=502;
	private  StringBuffer  buf=new StringBuffer();
	Vector<Thread>  threads=new Vector<Thread>();
	
	class SendThread  implements Runnable{
		
		private Socket socket;
		private String  cmd;
		
		public SendThread(Socket socket,String cmd){
			this.socket=socket;
			this.cmd=cmd;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				OutputStream  os=socket.getOutputStream();
				//os.write(Convert.str2Bcd(cmd));
				os.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	class ReceiveThread  implements Runnable{
		
		private  Socket socket;
		
		public ReceiveThread(Socket socket){
			this.socket=socket;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				DataInputStream  dis=new DataInputStream(socket.getInputStream());
				ByteArrayOutputStream  baos=new ByteArrayOutputStream();
				int size=0;
				byte[] buffer=new byte[50];
				while((size=dis.read(buffer))!=-1){
					baos.write(buffer, 0, size);
				}
			//	System.out.println(Convert.bytesToHexString(buffer)+" buffer");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}
	
	
	
	
	
	
	
	public  void   start(String cmd){
		try {
			Socket socket=new Socket(host, port);
			Thread st=new Thread(new SendThread(socket, cmd));//�����߳�;
			Thread rt=new Thread(new ReceiveThread(socket));//�����߳�;
			threads.add(st);
			threads.add(rt);
			st.start();
			rt.start();
			for(Thread ithread:threads){
				try {
					ithread.join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	};
	
	
	public static void main(String[] args) {
		
		String[]  str=new String[4];
		
		for (int j=0;j<4;j++)
		{
			str[j]="15010000000b0310000"+(2*j)+"000204a"+(j+1)+"40ffff";
			System.out.println(str[j]);
		}
		
		
		
		
		for(int i=0;i<str.length;i++)
		{
			//String cmd="15010000000b03100006000204a4400000";
			try {
				new TcpMaster().start(str[i]);
				new Thread().sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		/*String  cmd="15010000000b03100002000204a240ffff";
		new TcpMaster().start(cmd);*/
	}


	public StringBuffer getBuf() {
		return buf;
	}


	public void setBuf(StringBuffer buf) {
		this.buf = buf;
	}



	
	
	
}
